package org.coderfun.fieldmeta.common;

import java.util.concurrent.TimeUnit;

import org.coderfun.common.exception.AppException;
import org.coderfun.member.core.exception.MemberErrorCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;


@Service
public class EmailCaptchaServiceImpl implements EmailCaptchaService {
	@Autowired
	JavaMailSender jms;
	
	@Value("${spring.mail.username}")
	String username;

	@Value("${register.captcha.expire}")
	int captchaExpire;

	@Autowired
	RedisTemplate<String, String> redisTemplate;

	@Override
	public void send(String email) {
		
		//验证码未过期
		if (redisTemplate.opsForValue().get(getRedisCaptchaKey(email)) != null) {
			throw new AppException(MemberErrorCode.CAPTCHA_NOT_EXPIRED);
		}
		
		// TODO Auto-generated method stub
		// 建立邮件消息
		SimpleMailMessage mainMessage = new SimpleMailMessage();
		mainMessage.setFrom("fieldmeta<" + username + ">");
		mainMessage.setTo(email);
		mainMessage.setSubject("fieldmeta 邮箱验证");
		String captcha = generateCaptcha();
		mainMessage.setText("验证码：" + captcha + "，提示：" + captchaExpire + "秒后自动过期！");
		jms.send(mainMessage);
		
		
		// redis 保存验证码，并设置过期时间
		redisTemplate.opsForValue().set(getRedisCaptchaKey(email), captcha, 
				captchaExpire, TimeUnit.SECONDS);
	}
	
	private String getRedisCaptchaKey(String email) {
		return EMAIL_CAPTCHA_KEY_PREFIX + email;
	}

	private String generateCaptcha() {
		return String.valueOf((int)((Math.random() * 9 + 1) * 100000));
	}

	@Override
	public boolean valid(String email, String captcha) {
		String captchaStored = redisTemplate.opsForValue().get(getRedisCaptchaKey(email));
		if (captchaStored != null) {
			return captchaStored.equals(captcha);
		}
		return false;
	}
	
}
